package com.ceo.auth.service.impl;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ceo.auth.dto.AucLoginDTO;
import com.ceo.auth.entity.AucUser;
import com.ceo.auth.jwt.JwtEntity;
import com.ceo.auth.jwt.JwtUtil;
import com.ceo.auth.mapper.AucUserMapper;
import com.ceo.auth.service.AucUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ceo.common.http.exception.PlatformException;
import com.ceo.common.http.response.DefaultResponse;
import com.ceo.common.query.QueryParameter;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author ceo
 * @since 2023-06-02
 */
@Service
public class AucUserServiceImpl extends ServiceImpl<AucUserMapper, AucUser> implements AucUserService {

    @Resource
    AucUserMapper aucUserMapper;

    /**
     * 登录
     *
     * @param userAgent
     * @param aucLoginDTO
     * @return
     */
    @Override
    public String login(String userAgent, AucLoginDTO aucLoginDTO) {
        UserAgent ua = UserAgentUtil.parse(userAgent);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        AucUser user = lambdaQuery().eq(AucUser::getUserId, aucLoginDTO.getUserId()).one();
        if (user == null) {
            throw new PlatformException("用户不存在", 11010002);
        }
        if (1 == user.getState()) {
            throw new PlatformException("用户已锁定", 11010004);
        }
        if (2 == user.getState()) {
            throw new PlatformException("用户已注销", 11010014);
        }

        if (JwtUtil.checkPwd(aucLoginDTO.getPassword(), user.getPassword())) {
            JwtEntity jwtEntity = new JwtEntity(
                    user.getId(),
                    user.getUserId(),
                    user.getUserName(),
                    ua.isMobile() ? "mobile" : "WEB"
            );
            String token = JwtUtil.createToken(jwtEntity);
            Cookie cookie = new Cookie("Authorization", token);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
            return token;
        }else{
            throw new PlatformException(11010001,"用户名或密码错误");
        }
    }

    @Override
    public Long countNotDelUser(String userId) {
        return lambdaQuery()
                .eq(AucUser::getUserId, userId).count();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUser(AucUser aucUser) {
        String password = aucUser.getPassword();
        aucUser.setPassword(JwtUtil.getMD5Pwd(password));
        return save(aucUser);
    }

    @Override
    public Page<AucUser> queryUserPageWithSql(QueryParameter<AucUser> qp) {
        QueryWrapper<AucUser> wrapper = qp.createWrapper();
        if (StringUtils.isEmpty((CharSequence) qp.get_params().get("state"))){
            wrapper.and(wa -> wa.eq("state", 0).or().eq("state", 1 ));
        }
        aucUserMapper.queryUserPageWithSql(qp.getPage(), wrapper);
        return null;
    }


}
